package cn.elead.chaos.sso.server.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import cn.elead.chaos.sso.core.handler.LoginSuccessHandler;
import cn.elead.chaos.sso.core.user.LoginUser;
import cn.elead.chaos.sso.server.utli.Current;
import cn.elead.chaos.sso.server.web.login.service.RedisSaveService;
import cn.elead.chaos.sso.server.web.system.domain.SysUser;
import cn.elead.chaos.sso.server.web.system.mapper.SysUserMapper;
import cn.hutool.core.util.ObjectUtil;

/**
 * 登录成功
 * 
 * @author Administrator
 *
 */
public class LoginSuccessHandlerImpl implements LoginSuccessHandler {


	@Autowired
	private RedisSaveService redisSaveService;

	@Autowired
	private SysUserMapper userMapper;

	@Override
	public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, LoginUser user) {
		
		SysUser sysUser = redisSaveService.getSysUser(user.getUserId());
		if (ObjectUtil.isEmpty(sysUser)) {
			sysUser = userMapper.selectUserById(user.getUserId());
			if (ObjectUtil.isNotNull(sysUser)) {
				Current.bind(sysUser);
				redisSaveService.saveSysUserToRedis(user.getUserId(), sysUser);
			}
		} else {
			Current.bind(sysUser);
		}
	}

	@Override
	public void onEnd(HttpServletRequest request, HttpServletResponse response, LoginUser user) {
		Current.unbindUser();
	}

}
